
import 'package:bot_toast/bot_toast.dart';
import 'package:event_bus/event_bus.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:get_storage/get_storage.dart';
import 'package:self32/util/camera_util.dart';

import 'entity/current_task_entity.dart';
import 'entity/setting_entity.dart';
import 'http/api_url.dart';
import 'log/logger_manager.dart';
import 'page/index_page.dart';
import 'socket/socket.dart';
import 'socket/socket_helper.dart';
import 'tts/tts_helper.dart';
import 'util/clock.dart';
import 'util/timer_manager.dart';


void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  tts = TtsHelper()..initTTS();
  // await LoggerManager().initLogger();
  eventFactory = EventBus();
  await LoggerManager().initLogger();
  await GetStorage.init();
  final box = GetStorage();
  if(box.hasData('setting_entity')){
    settingEntity = SettingEntity.fromJson(box.read("setting_entity"));

    if(settingEntity.websocketAddr != null){
      websocket = settingEntity.websocketAddr!;
    }
    if(settingEntity.sip2ApiAddr != null){
      sip2ApiUrl = 'http://${settingEntity.sip2ApiAddr!}:60060';
      faceUrl = 'http://${settingEntity.sip2ApiAddr!}:10040';
    }
  }else{
    settingEntity = SettingEntity();
  }

  FlutterError.onError = (FlutterErrorDetails details) async {
    // LoggerManager().write("error", '${details.exception}\r\n${details.stack}');
    print('${details.exception}\r\n${details.stack}');
  };

  try{
    if(websocket!=null && websocket != ""){
      socketHelper = SocketHelper(websocket!);
    }
  }catch(e){
    print('websocket连接失败');
  }


  currentTask = CurrentTaskEntity();

  timer = TimerManager()..setCountDownTime(actionTimeCountdown: settingEntity.actionTime);
  clock = Clock()..start();

  runApp(const MyApp());

}


late EventBus eventFactory;
late SocketHelper socketHelper;
late SettingEntity settingEntity;
late TimerManager timer;
late Clock clock;
late TtsHelper tts;
late CurrentTaskEntity currentTask;
CameraUtil camera = CameraUtil();


class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return  ScreenUtilInit(
      designSize: const Size(720, 405),
      minTextAdapt: true,
      splitScreenMode: true,
      builder: (_ , child) {
        return  GetMaterialApp(
            debugShowCheckedModeBanner: false,
            theme: ThemeData(
              fontFamily: 'pingfang',
            ),
            routingCallback: (routing){
              if(routing!.current == '/'){
                camera.disposeCurrentCamera();
              }
            },
            builder: BotToastInit(),
            home: const Index()
        );
      },
    );
  }
}
